using System;
using System.Linq;
using Datacollection.Data.Models;
using Datacollection.Services.Logging;

namespace Datacollection.DataProcessing
{
    /// <summary>
    /// 测试数据解析器（兼容.NET Framework 4.xDatacollection
    /// </summary>
    public class TestDataParser
    {
        /// <summary>
        /// 解析测试数据字符串
        /// </summary>
        public TestSummary Parse(string data)
        {
            try
            {
                var summary = new TestSummary();
                data = data?.Trim() ?? string.Empty;
                
                // 按分号分割测试项
                var testItems = data.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Select(item => item.Trim()) // 手动修剪每个项
                                   .ToArray();
                
                // 处理整体失败标记
                if (testItems.Length > 0 && testItems.Last().Equals("FAIL", StringComparison.OrdinalIgnoreCase))
                {
                    summary.IsFailed = true;
                    testItems = testItems.Take(testItems.Length - 1).ToArray();
                }

                // 解析每个测试项
                foreach (var item in testItems)
                {
                    // 按逗号分割字段（兼容旧框架：手动Trim每个字段）
                    var fields = item.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select(field => field.Trim()) // 手动修剪每个字段
                                    .ToArray();
                    
                    if (fields.Length < 3)
                    {
                        LogServiceLocator.Logger.Warn($"无效的测试数据格式: {item}");
                        continue;
                    }

                    // 根据测试类型解析
                    switch (fields[3].ToUpper())
                    {
                        case "DCR":
                            ParseDcrTest(fields, summary);
                            break;
                        case "IW":
                            ParseIwTest(fields, summary);
                            break;
                        case "IR":
                        case "HIPOT":
                            ParseIrHipotTest(fields, summary);
                            break;
                        default:
                            LogServiceLocator.Logger.Warn($"未知的测试类型: {fields[3]}，数据: {item}");
                            break;
                    }
                }

                summary.EndTime = DateTime.Now;
                LogServiceLocator.Logger.Info($"数据解析完成，共解析 {summary.TestItems.Count} 个测试项，整体结果: {(!summary.IsFailed ? "通过" : "失败")}");
                return summary;
            }
            catch (Exception ex)
            {
                LogServiceLocator.Logger.Error($"解析测试数据时发生错误", ex);
                throw;
            }
        }

        /// <summary>
        /// 解析DCR测试项
        /// </summary>
        private void ParseDcrTest(string[] fields, TestSummary summary)
        {
            if (fields.Length < 6)
            {
                LogServiceLocator.Logger.Warn($"DCR测试数据格式不正确: {string.Join(",", fields)}");
                return;
            }

            try
            {
                var result = new DcrTestResult
                {
                    TestId = int.Parse(fields[0]),
                    Channel1 = int.Parse(fields[1]),
                    Channel2 = int.Parse(fields[2]),
                    TestType = fields[3],
                    Status = fields[5]
                };

                // 解析测量值和单位（如"49.11mohm"）
                var valueStr = fields[4];
                var numericPart = new string(valueStr.Where(c => char.IsDigit(c) || c == '.').ToArray());
                var unitPart = new string(valueStr.Where(c => !char.IsDigit(c) && c != '.').ToArray()).Trim();

                result.Value = double.Parse(numericPart);
                result.Unit = unitPart;
                result.Barcode = summary.Barcode;

                summary.TestItems.Add(result);
            }
            catch (Exception ex)
            {
                LogServiceLocator.Logger.Error($"解析DCR测试数据时出错: {string.Join(",", fields)}", ex);
            }
        }

        /// <summary>
        /// 解析IW测试项
        /// </summary>
        private void ParseIwTest(string[] fields, TestSummary summary)
        {
            if (fields.Length < 8)
            {
                LogServiceLocator.Logger.Warn($"IW测试数据格式不正确: {string.Join(",", fields)}");
                return;
            }

            try
            {
                var result = new IwTestResult
                {
                    TestId = int.Parse(fields[0]),
                    Channel1 = int.Parse(fields[1]),
                    Channel2 = int.Parse(fields[2]),
                    TestType = fields[3],
                    Value1 = double.Parse(fields[4]),
                    Status1 = fields[5],
                    Value2 = double.Parse(fields[6]),
                    Status2 = fields[7],
                    Barcode = summary.Barcode
                };

                summary.TestItems.Add(result);
            }
            catch (Exception ex)
            {
                LogServiceLocator.Logger.Error($"解析IW测试数据时出错: {string.Join(",", fields)}", ex);
            }
        }

        /// <summary>
        /// 解析IR和HIPOT测试项
        /// </summary>
        private void ParseIrHipotTest(string[] fields, TestSummary summary)
        {
            if (fields.Length < 6)
            {
                LogServiceLocator.Logger.Warn($"{fields[3]}测试数据格式不正确: {string.Join(",", fields)}");
                return;
            }

            try
            {
                // 提取条码信息（如"123456789ABC"）
                //if (!string.IsNullOrEmpty(fields[1]) && fields[1].Length > 5)
                //{
                //    summary.Barcode = fields[1];
                //}

                var result = new IrHipotTestResult
                {
                    TestId = int.Parse(fields[0]),
                    Channel1 = fields[1],
                    Channel2 = fields[2],
                    TestType = fields[3],
                    Status = fields[5],
                    Barcode = summary.Barcode
                };

                // 解析测量值和单位
                var valueStr = fields[4];
                var numericPart = new string(valueStr.Where(c => char.IsDigit(c) || c == '.' || c == '-').ToArray());
                var unitPart = new string(valueStr.Where(c => !char.IsDigit(c) && c != '.' && c != '-').ToArray()).Trim();

                result.Value = double.Parse(numericPart);
                result.Unit = unitPart;
                result.Channel1 = fields[1];
                result.Channel2 = fields[2];

                summary.TestItems.Add(result);
            }
            catch (Exception ex)
            {
                LogServiceLocator.Logger.Error($"解析{fields[3]}测试数据时出错: {string.Join(",", fields)}", ex);
            }
        }
    }
}
    